<script setup lang="ts">
import dayjs from 'dayjs'
import { useLoadMore } from 'vue-request'
import { fetchPaymentRecordAPI } from '@/apis/fetchPaymentRecord'
import { useUserInfoStore } from '@/store/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()

/* ------------------------------- 列表数据 START ------------------------------- */
// 项目数据
const { dataList, loading, loadingMore, noMore, loadMore, refresh } = useLoadMore<LoadMoreData<PaymentRecord>>(
  fetchPaymentRecord,
  { isNoMore: d => d?.list.length === d?.total },
)
// 搜索
const { searchText, isOpenSearch, searching, searchResult, fetchSearchResult } = useSearch<PaymentRecord>(search as any)

const finalList = computed(() => {
  if (isOpenSearch.value)
    return searchResult.value
  else
    return dataList.value
})

const skeletonLength = ref(6)

watch(finalList, (newVal) => {
  if (newVal.length > 0)
    skeletonLength.value = newVal.length
})

watch(searching, (newVal) => {
  if (newVal)
    uni.showLoading({ title: '搜索中...' })
  else
    uni.hideLoading()
})

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

/**
 * @description useLoadMore 所必需的服务函数
 *
 * @param d - useLoadMore 中的 `data`
 */
async function fetchPaymentRecord(d?: LoadMoreData<PaymentRecord>): Promise<LoadMoreData<PaymentRecord>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1
  // 发起请求
  const res = await fetchPaymentRecordAPI({
    page: _page.toString(),
    limit: '10',
  }, userInfoStore.userInfo!.token!)
  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

async function search() {
  const res = await fetchPaymentRecordAPI({
    page: '1',
    limit: '100',
    keyword: searchText.value.length > 0 ? searchText.value : undefined,
  }, userInfoStore.userInfo!.token!)
  return res.data!
}

onShow(() => refresh())
onReachBottom(() => loadMore())
/* -------------------------------- 列表数据 END -------------------------------- */

function getPaymentNodeName(payNode?: string) {
  if (payNode === '1')
    return '首期款'
  else if (payNode === '2')
    return '中期款'
  else if (payNode === '3')
    return '尾款'
}

function getTableInfo(payment: PaymentRecord) {
  return [
    ['打款节点', '打款金额', '打款时间'],
    [
      getPaymentNodeName(payment.pay_node) || '未知',
      payment.pay_money ? `¥${payment.pay_money}` : '未知',
      dayjs.unix(payment.create_time!).format('YYYY-MM-DD') || '未知',
    ],
  ]
}

const handleSearch = useDebounceFn((keyword: string) => {
  searchText.value = keyword
  fetchSearchResult()
}, 500)

function handleTapPayment(paymentId?: string, projectId?: string) {
  if (paymentId && projectId) {
    router.push({
      name: 'paymentDetail',
      params: {
        payment_id: paymentId,
        project_id: projectId,
      },
    })
  }
  else {
    uni.showToast({ title: '发生错误', icon: 'none' })
  }
}
</script>

<template>
  <view class="flex flex-col min-h-screen bg-#F8F8F8">
    <view class="z-100 sticky top-0 left-0 w-750rpx bg-white">
      <Spacer height="30" />
      <view class="mx-30rpx border-1px border-solid border-#E3E3E3 rounded-6rpx">
        <uv-search
          shape="square" bg-color="#F8F9FD" border-color="#E3E3E3" color="#000000" search-icon-size="36rpx"
          search-icon-color="#FF6D0A" placeholder-color="#999999" :show-action="false"
          height="74rpx" placeholder="请输入业主姓名、手机号" @change="handleSearch" @focus="isOpenSearch = true" @blur="isOpenSearch = false"
        />
      </view>
      <Spacer height="30" />
    </view>
    <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
    <uv-list v-if="finalList.length > 0" :custom-style="{ padding: '30rpx', backgroundColor: '#F8F8F8' }">
      <uv-list-item
        v-for="payment in finalList" :key="payment.id"
        :custom-style="{ borderRadius: '20rpx', marginBottom: '30rpx' }"
      >
        <view class="flex flex-col bg-white rounded-20rpx" @tap="handleTapPayment(`${payment.id}`, `${payment.project_id}`)">
          <view class="relative pt-30rpx pr-30rpx pb-32rpx pl-30rpx">
            <view class="text-28rpx leading-28rpx text-secondary">
              {{ payment.name || '未知' }}
            </view>
            <view class="flex items-center mt-20rpx text-28rpx leading-28rpx">
              <view class="text-tertiary">
                业务员：
              </view>
              <view class="text-secondary">
                {{ payment.salesman_name || '未知' }}
              </view>
            </view>
          </view>
          <Divider />
          <view class="pt-30rpx px-30rpx">
            <Table
              :data="getTableInfo(payment)"
            />
          </view>
          <Divider />
          <view class="flex flex-row-reverse justify-between items-center p-30rpx">
            <view class="flex">
              <RGButton
                class="ml-18rpx"
                size="medium"
                corner="small"
                type="primary"
                @tap="handleTapPayment(`${payment.id}`, `${payment.project_id}`)"
              >
                查看详情
              </RGButton>
            </view>
            <view class="flex items-center">
              <view class="text-30rpx leading-30rpx text-secondary font-bold">
                张三
              </view>
              <view class="flex-shrink-0 ml-5rpx px-22rpx py-5rpx text-24rpx leading-24rpx text-white bg-brand rounded-full">
                业主
              </view>
            </view>
          </view>
        </view>
      </uv-list-item>
      <uv-load-more v-if="finalList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
    </uv-list>
    <PageDefault v-else />
  </view>
</template>

<route lang="yaml">
name: 'paymentRecord'
style:
  navigationBarTitleText: '收款记录'
layout: 'custom'
</route>
